package com.pansoft.xbrl.xbrljson.util;

import com.pansoft.xbrl.xbrljson.model.Context;
import com.pansoft.xbrl.xbrljson.model.ContextDim;
import com.pansoft.xbrl.xbrljson.model.TypedMember;
import com.pansoft.xbrl.xbrljson.object.ContextDimComp;

import java.util.Collections;
import java.util.List;

/**
 * 上下文使用工具类
 * @author coolmayi
 *
 */
public class ContextUtil {

	
	public static String createContextId(Context context) {
		
		if (context == null) {
			return null;
		}
		
//		As_Of_2020_03_28_TypesOfEInvoiceAxis_OrdinaryVatEInvoiceMember_GoodsOrServicesNumberLineNumberAxis_1_UniqueCodeOfInvoiceLineNumberAxis_01100190021122595386
		StringBuilder sb = new StringBuilder();
		sb.append("As_Of_");
		if (context.getPeriodType() == Context.ContextPeriodInstant) {
			sb.append(context.getInstDate().replaceAll("-","_"));
		} else {
			sb.append(context.getStartDate().replaceAll("-","_") + "_" + context.getEndDate().replaceAll("-","_"));
		}
		List<ContextDim> contextDimList = context.getScenarioList();
		
		if (contextDimList != null) {
			Collections.sort(contextDimList, new ContextDimComp());
			for (ContextDim dim : contextDimList) {
				sb.append("_");
				String dimId = dim.getDimension();
				dimId = getElementName(dimId);
				if (dim instanceof TypedMember) {
					TypedMember tMember = (TypedMember)dim;
					sb.append(dimId + "_" + tMember.getMemberValue());
				} else {
					sb.append(dimId + "_" + getElementName(dim.getMember()));
				}
			}
		}
		
		return sb.toString();
	}
	
	
	/**
	 * 删除命名空间前缀
	 * @param elementInfo
	 * @return
	 */
	private static String getElementName(String elementInfo) {
		
		if (elementInfo == null) {
			return elementInfo;
		}
		
		String ret = elementInfo;
		int pos = elementInfo.indexOf(":");
		if ( pos >=0 ) {
			ret = elementInfo.substring(pos +1 , elementInfo.length());
		}
		
		return ret;
	}
	
}
